using Microsoft.Extensions.Logging;
using SumerCoreDevOps.Infrastructure.Tcp;
using SumerCoreDevOps.Shared.Enums;
using SumerCoreDevOps.Shared.Models.Messages;

namespace SumerCoreDevOps.ExecuteNodeApi.Handlers;

/// <summary>
/// 清理处理器
/// </summary>
public class CleanupHandler : IStepHandler
{
    private readonly ILogger<CleanupHandler> _logger;
    private readonly TcpClient _tcpClient;

    public CleanupHandler(ILogger<CleanupHandler> logger, TcpClient tcpClient)
    {
        _logger = logger;
        _tcpClient = tcpClient;
    }

    public async Task<StepExecutionResult> ExecuteAsync(WorkflowStepDispatchMessage message)
    {
        try
        {
            var workDir = message.WorkDirectory;

            if (string.IsNullOrEmpty(workDir) || !Directory.Exists(workDir))
            {
                return new StepExecutionResult
                {
                    Success = true,
                    Progress = 100,
                    OutputContext = new Dictionary<string, string>
                    {
                        ["CLEANUP_STATUS"] = "NoDirectory"
                    }
                };
            }

            // 计算目录大小
            var dirInfo = new DirectoryInfo(workDir);
            long totalSize = 0;
            int fileCount = 0;

            foreach (var file in dirInfo.GetFiles("*", SearchOption.AllDirectories))
            {
                totalSize += file.Length;
                fileCount++;
            }

            var freedSpaceMB = totalSize / 1024 / 1024;

            // 删除目录
            var remainingFiles = new List<string>();

            try
            {
                Directory.Delete(workDir, true);
                _logger.LogInformation("清理目录成功: {Directory}, 文件数: {Count}, 释放空间: {Size}MB",
                    workDir, fileCount, freedSpaceMB);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "清理目录部分失败: {Directory}", workDir);

                // 尝试获取残留文件
                if (Directory.Exists(workDir))
                {
                    remainingFiles.AddRange(Directory.GetFiles(workDir, "*", SearchOption.AllDirectories));
                }
            }

            // 发送清理结果
            var cleanupResult = new CleanupResultMessage
            {
                TaskId = message.TaskId,
                Success = remainingFiles.Count == 0,
                DeletedFileCount = fileCount - remainingFiles.Count,
                FreedSpaceMB = freedSpaceMB,
                RemainingFiles = remainingFiles,
                ErrorMessage = remainingFiles.Count > 0 ? "部分文件清理失败" : null
            };

            await _tcpClient.SendMessageAsync(TcpMessageType.CleanupResult, cleanupResult);

            return new StepExecutionResult
            {
                Success = true,
                Progress = 100,
                OutputContext = new Dictionary<string, string>
                {
                    ["CLEANUP_FILES"] = fileCount.ToString(),
                    ["CLEANUP_SPACE_MB"] = freedSpaceMB.ToString(),
                    ["CLEANUP_REMAINING"] = remainingFiles.Count.ToString()
                }
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "清理处理器执行失败");
            return new StepExecutionResult
            {
                Success = false,
                ErrorMessage = ex.Message
            };
        }
    }
}
